<!-- [COMPONENT] : 自定义多选下拉框
原装的参数为数组[1, 2]  转化为字符串参数 ”1,2“
-->
<template>
  <el-select
    ref="select"
    :value="internalArray"
    :multiple="multiple"
    v-bind="$attrs"
    @input="handleInput"
    @change="handleChange"
  >
    <slot></slot>
  </el-select>
</template>

<script>
export default {
  name: 'StringMultipleSelect',
  props: {
    value: {
      type: [String, Number],
      default: ''
    },
    multiple: {
      type: Boolean,
      default: true
    },
    separator: {
      type: String,
      default: ','
    }
  },
  data() {
    return {
      internalArray: []
    }
  },
/*
  created() {
    if (this.multiple) {
      // 将字符串转换为数组
      this.internalArray = this.value ? this.value.split(this.separator)
          .filter(item => item !== '')
          .map(item => Number(item) ? Number(item) : item)
        : []
    }else{
      this.internalArray = this.value
    }
  },
*/

  watch: {
    value: {
      immediate: true,
      handler(newVal) {
        if (!this.multiple) {
          this.internalArray = newVal
          return;
        }
        // 将字符串转换为数组
        this.internalArray = newVal ? newVal.split(this.separator)
            .filter(item => item !== '')
            .map(item => Number(item) ? Number(item) : item)
          : []
        console.log("--------", this.internalArray)
      }
    }
  },
  methods: {
    handleInput(value) {
      this.internalArray = value
    },
    handleChange(value) {
      let stringValue = value;
      if (this.multiple) {
        // 将数组转换为字符串并触发 input 事件
        stringValue = value.join(this.separator)
      }
      this.$emit('input', stringValue)
      this.$emit('change', stringValue, value)
    },
    // 提供方法获取当前值
    getArrayValue() {
      return this.internalArray
    },
    getStringValue() {
      return this.internalArray.join(this.separator)
    }
  }
}
</script>
